package com.wzapp.sitposture.common.util;

import com.wzapp.sitposture.common.error.ErrorMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * 功能: <br/>
 *
 * @author ql
 * @version 0.4
 * @create 2018-06-28 18:31
 **/
@Component
public class ResourceBundleUtil {
    private static final Logger log = LoggerFactory.getLogger(ResourceBundleUtil.class);

    @Autowired
    private MessageSource messageSource;

    /**
     * 从国际化文件中寻找错误
     */
    public void parseErrorMessage(ErrorMessage errorMessage, String[] args, String error) {

        Locale locale = LocaleContextHolder.getLocale();
        if (null != error) {
            try {
                error = messageSource.getMessage(error, args, locale);
            } catch (Exception e) {
                log.info("解析国际化错误：" + e.getMessage(),e);
            }
            if (error.contains("#")) {
                String[] errors = error.split("#");
                errorMessage.setCode(Integer.valueOf(errors[0]));
                errorMessage.setMessage(errors[1]);
            } else {
                errorMessage.setMessage(error);
            }
        }
    }

    /**
     * 从国际化文件中寻找错误
     */
    public ErrorMessage parseErrorMessage(String error,String[] args) {

        ErrorMessage errorMessage = new ErrorMessage();
        Locale locale = LocaleContextHolder.getLocale();
        if (null != error) {
            try {
                error = messageSource.getMessage(error, args, locale);
            } catch (Exception e) {
                log.info("解析国际化错误：" + e.getMessage(),e);
            }
            if (error.contains("#")) {
                String[] errors = error.split("#");
                errorMessage.setCode(Integer.valueOf(errors[0]));
                errorMessage.setMessage(errors[1]);
            } else {
                errorMessage.setMessage(error);
            }
        }
        return errorMessage;
    }
}
